import { defineComponent, h, reactive, watch } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElImage, ElIcon, ElEmpty, ElTooltip, ElMessage, ElForm, ElFormItem, ElTag, ElInput, ElButton, ElSelect, ElOption, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { QuestionFilled, Picture as IconPicture } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

import Drawer from '@renderer/components/drawer'
import { getMakeGroupFriendDetail, getMakeGroupFriendDetailList, exportMakeGroupFriendDetailExport } from '@renderer/ajax/api/addGroupBuddy'
import ZWRenderOverflowTootip from '@renderer/components/win/ZWRenderTableColumn/ZWRenderOverflowTootip.vue'
import { useExpose } from '@renderer/utils'
import { toBuffer } from '@renderer/utils/utils'
import { WEICHAT_SRARUS_LIST } from '@renderer/enums/common'

import styles from './Detail.module.scss'

const { ipcRenderer } = require("electron");
const fs = require('fs')

export default defineComponent({
    name: 'Detail',
    setup(props, { emit, slots }) {
        const drawerData = reactive({
            visible: false,
            title: '活动标题',
            width: '860px'
        })
        const state = reactive({
            row: {},
            params: {
                id: '',
                title: '', // 标题
                // 0 全部 1 未发送 2 已发送 3 已通过 4 发送失败 5已是好友
                status: 0,
                page: 1,
                pageSize: 15,
            },
            list: [],
            total: 0,
            title: '',
            Data: {
                id: 0,
                title: '',
                groupChatList: [],
                exclusionType: [],
                exclusionNickName: [],
                exclusionCompanyName: [],
                verifyMessage: '', // 验证信息
                autoRemarksMsg: '', // 自动备注信息
                custTagList: [],
                status: 1,
                createdAt: ''
            }
        })
        const onExport = async () => {
            const res: any = await exportMakeGroupFriendDetailExport({ Id: state.row.id, Title: state.params.title, Statue: state.params.status })
            
            let params = {
                title: '请选择下载文件的目录',
                buttonLabel: '保存',
                pathName: `${state.Data.title || ''}_${dayjs(state.Data.createdAt).format('YYYY_MM_DD')}.xlsx`,
            }
            let buf = toBuffer(res)
            ipcRenderer.invoke("open-savebox", params).then((res) => {
                fs.writeFileSync(res.filePath, buf)
                res && ElMessage.success('导出成功')
            });
        }
        const onState = async (row: any) => {
            state.row = row
            drawerData.visible = true
            state.params.id = row.id
            const res: any = await Promise.allSettled([
                getMakeGroupFriendDetail({ id: row.id }),
                getMakeGroupFriendDetailList({
                    ...state.params,
                    page: 1,
                    pageSize: 15,
                })
            ])

            const [ DataRes, listRes ] = res

            // 详情列表
            if (listRes.status === 'fulfilled') {
                state.list = listRes?.value?.data || []
                state.total = listRes?.value?.total || 0
            }

            if (DataRes.status === 'fulfilled') {
                state.Data = DataRes.value || {}
                drawerData.title = `${row.title} (${renderTaskStatus()})`
            }

        }
        const getList = async () => {
            const res: any = await getMakeGroupFriendDetailList(state.params)
            state.list = res?.data || []
            state.total = res?.total || 0

        }
        let timeout: any
        const onSearch = () => {
            if (timeout) clearTimeout(timeout)
            timeout = setTimeout(async () => {
                getList()
            }, 400)
        }
        const onSizeChange = (v: number) => {
            state.params.page = 1;
            getList()
        };
        const onCurrentChange = (v: number) => {
            getList()
        };
        let timer: any = null
        // 开启定时器
        const startTimer = () => {
            console.log('开启定时器')
            timer = setInterval(() => {
                onState(state.row)
            }, 5000)
        }
        // 关闭定时器
        const closeTime = () => {
            console.log('关闭定时器')
            clearInterval(timer)
            state.params.id = ''
            state.params.title = ''
            state.params.status = 0
        }
        watch(
            () => drawerData.visible,
            (v) => (v ? startTimer() : closeTime())
        )
        useExpose({
            onState
        })
        const renderError = (row: any) => {
            return (
                <div class={styles.error}>
                    { (WEICHAT_SRARUS_LIST.find(item => item.value === row.status) || {}).label || '--'}
                    {
                        row.errorMsg && <ElTooltip effect="dark" content={row.errorMsg} placement="top">
                            <ElIcon>
                                <QuestionFilled />
                            </ElIcon>
                        </ElTooltip>
                    }
                </div>
            )
        }
        // 渲染群聊
        const renderGroup = () => {
            const groupList = state.Data.groupChatList
            if (!groupList?.length) {
                return '--'
            }

            const groupNameContent = `${groupList.map(item => item.name).join('、')}`

            let div = document.createElement('div')
            let isOverFlow = false
            div.innerHTML = groupNameContent
            div.className = 'zw-text-ellipsis2'
            div.style.zIndex = '-99999999'
            div.style.verticalAlign = "middle"
            div.style.width = "707px"

            document.body.appendChild(div)
            if (div.clientHeight + 3 < div.scrollHeight || div.clientWidth < div.scrollWidth) {
                isOverFlow = true
            }
            document.body.removeChild(div)
            div = null

            const overText = isOverFlow ? '...等共' + groupList.length + '个群' : ''
            const renderTooltip = (
                <ElTooltip
                    effect="dark"
                    content={groupNameContent}
                    placement="top"
                    showAfter={800}
                    popperStyle={{
                        maxWidth: '560px',
                    }}
                >
                    <div id="groupDetailName" >
                        <div class="zw-text-ellipsis2">
                            {groupNameContent.substring(0, 126 - overText.length)}
                            {overText}
                        </div>
                    </div>
                </ElTooltip>
            )
            return renderTooltip
        }
        // 渲染标签
        const renderTag = () => (
            <div class={styles["detail-render-tags"]}>
                {state.Data.custTagList?.length
                    ? state.Data.custTagList.map((item) => (
                        <ElTag key={item.id} type={item.isDelete ? "info" : ""}>
                            {item.name}
                        </ElTag>
                    ))
                    : "无"}
            </div>
        );
        // 渲染任务状态
        const renderTaskStatus = () => {
            const text = ['', '未开始', '进行中', '已暂停', '已完成']
            return text[state.Data.status]
        }
        // 
        const renderInfo = (row: any) => (
            <div class={styles.column_info}>
                <ElImage
                    class={styles.avatar}
                    src={row.avatorUrl}
                    vSlots={{
                        error: () => (
                            <ElIcon class={styles.avatar}>
                                <IconPicture />
                            </ElIcon>
                        )
                    }}
                />
                <div class={styles.column_info_name}>{row.name}</div>
            </div>
        )
        
        // 渲染所在群
        const formatterGroupInfo = (row) => {
            return row.groupChatList?.map((item) => item.Name).join('、') || '--'
        }
        return () => (
            <>
                <Drawer state={drawerData}>
                    {{
                        default: () => (
                            <div class={styles.drawer_content}>
                                <div class={styles.info}>
                                    <ElDescriptions column={1}>
                                        <ElDescriptionsItem label="所选群聊：">
                                            {renderGroup()}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="客户标签：" >
                                            {renderTag()}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="自动备注：">
                                            {state.Data.autoRemarksMsg || '--'}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="创建时间：">
                                            {state.Data.createdAt || '--'}
                                        </ElDescriptionsItem>
                                    </ElDescriptions>
                                </div>
                                <ElForm class={styles.search} inline={true}>
                                    <div class={styles.fun}>
                                        <ElFormItem label="客户昵称">
                                            <ElInput class={styles.inp} vModel={state.params.title} onInput={onSearch} clearable placeholder="请输入昵称进行搜索" />
                                        </ElFormItem>
                                        <ElFormItem label="添加状态">
                                            <ElSelect
                                                style="width:100%"
                                                vModel={state.params.status}
                                                placeholder="请选择"
                                                onChange={getList}
                                            >
                                                {WEICHAT_SRARUS_LIST.map((item) => {
                                                    return (
                                                        <ElOption label={item.label} value={item.value} />
                                                    );
                                                })}
                                            </ElSelect>
                                        </ElFormItem>
                                        <ElFormItem>
                                            <ElButton class={styles.export_btn} type="primary" onClick={onExport}>
                                                导出
                                            </ElButton>
                                        </ElFormItem>
                                    </div>
                                </ElForm>
                                <div class={styles.table}>
                                    <ElTable
                                        data={state.list}
                                        maxHeight={600}
                                        vSlots={{
                                            default: () => (
                                                <>
                                                    <ElTableColumn label="客户信息" minWidth="150" vSlots={{ default: ({ row }) => renderInfo(row) }} />
                                                    <ElTableColumn label="所在群"  prop="groupChatList">
                                                        {{
                                                            default: ({ row }) => (
                                                                <ZWRenderOverflowTootip value={formatterGroupInfo(row)}></ZWRenderOverflowTootip>
                                                            )
                                                        }}
                                                    </ElTableColumn>
                                                    <ElTableColumn label="添加状态" minWidth="120" vSlots={{ default: ({ row }) => renderError(row) }} />
                                                    <ElTableColumn label="发送时间" minWidth="170" prop="requestedAt" vSlots={{ default: ({ row }) => row.requestedAt || '--' }} />
                                                    <ElTableColumn label="添加时间" minWidth="170" prop="passedAt" vSlots={{ default: ({ row }) => row.passedAt || '--' }} />
                                                </>
                                            ),
                                            empty: () => <ElEmpty />
                                        }}
                                    />
                                    <ElPagination
                                        class={styles.pagination}
                                        vModel:currentPage={state.params.page}
                                        vModel:pageSize={state.params.pageSize}
                                        page-sizes={[15, 30, 50, 100]}
                                        background
                                        layout="total,  prev, pager, next,sizes, jumper"
                                        total={state.total}
                                        onSizeChange={onSizeChange}
                                        onCurrentChange={onCurrentChange}
                                    />
                                </div>
                            </div>
                        )
                    }}
                </Drawer>
            </>
        )
    }
})
